package com.c2b.algorithm.leetcode.base;

/**
 * <a href='https://leetcode.cn/problems/maximum-average-subarray-i/'>子数组最大平均数 I(Maximum Average Subarray I)</a>
 * <p>给你一个由 n 个元素组成的整数数组 nums 和一个整数 k 。</p>
 * <p>请你找出平均数最大且 长度为 k 的连续子数组，并输出该最大平均数。</p>
 * <p>任何误差小于 10-5 的答案都将被视为正确答案。</p>
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：nums = [1,12,-5,-6,50,3], k = 4
 *      输出：12.75
 *      解释：最大平均数 (12-5-6+50)/4 = 51/4 = 12.75
 *
 * 示例 2：
 *      输入：nums = [5], k = 1
 *      输出：5.00000
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 * <ul>
 *     <li>n == nums.length</li>
 *     <li>1 <= k <= n <= 10^5</li>
 *     <li>-10^4 <= nums[i] <= 10^4</li>
 * </ul>
 * </p>
 *
 * @author c2b
 * @since 2023/11/9 17:11
 */
public class LC0643MaximumAverageSubarray_I_S {

    static class Solution {
        public double findMaxAverage(int[] nums, int k) {
            double currKSum = 0;
            for (int i = 0; i < k; i++) {
                currKSum += nums[i];
            }
            double maxKSum = currKSum;
            for (int i = k; i < nums.length; i++) {
                currKSum = currKSum - nums[i - k] + nums[i];
                maxKSum = Math.max(maxKSum, currKSum);
            }
            return maxKSum / k;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.findMaxAverage(new int[]{1, 12, -5, -6, 50, 3}, 4));
        System.out.println(solution.findMaxAverage(new int[]{1}, 1));
    }
}
